package com.wondream.myframework.app.common.aspect;

import com.wondream.myframework.app.common.annotation.SensitiveTable;
import com.wondream.myframework.app.common.util.SensitiveFieldUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.plugin.*;
import org.apache.ibatis.session.defaults.DefaultSqlSession;
import org.springframework.core.annotation.AnnotationUtils;

import java.util.List;
import java.util.Properties;

/**
 * 切面实现字段加解密
 */
@Intercepts({
        @Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})
})
@Slf4j
public class DbFieldInterceptor implements Interceptor {

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        if(!(invocation.getTarget() instanceof Executor && invocation.getArgs().length == 2)){
            return invocation.proceed();
        }
        MappedStatement statement = (MappedStatement) invocation.getArgs()[0];
        log.info("begin encrypt statement id:"+statement.getId());
        Object parameter = invocation.getArgs()[1];
        if(parameter instanceof DefaultSqlSession.StrictMap) {
            DefaultSqlSession.StrictMap map = (DefaultSqlSession.StrictMap)parameter;
            List list = (List) map.get("list");
            if(CollectionUtils.isEmpty(list)){
                return invocation.proceed();
            }
            SensitiveTable sensitiveData = AnnotationUtils.findAnnotation(list.get(0).getClass(), SensitiveTable.class);
            if(sensitiveData==null){
                return invocation.proceed();
            }
            list.forEach(obj -> {
//                SensitiveFieldUtils.encryptDBField(sensitiveData.table(), parameter);
            });
        }
        return invocation.proceed();
    }

    @Override
    public Object plugin(Object o) {
        return Plugin.wrap(o, this);
    }

    @Override
    public void setProperties(Properties properties) {

    }
}
